<?php

namespace App\Repositories\Ca;

use App\Facade\AppContext;
use App\Models\BaseModel;
use App\Models\Ca\ConsultationWay;
use App\Models\Ca\Docker;
use App\Repositories\BaseRepository;
use App\Traits\RequestCache;
use App\Utils\Output;
use App\Utils\TreeUtil;
use Illuminate\Support\Facades\DB;

class ConsultationWayRepository extends BaseRepository
{
    use RequestCache;

    function getName($id)
    {
        return $this->requestCache('name_' . $id, function () use ($id) {
            return ConsultationWay::query()->where('id', '=', $id)->value('name');
        });
    }

    public function adminPager(array $params)
    {
        extract($params);
        $query = ConsultationWay::query()->where('hospital_id', '=', AppContext::hospitalId());
        $query->orderByDesc('weight');
        $data = $query->get()->toArray();
        $dataList = TreeUtil::toFormat($data, 'name');
        $_data = [];
        foreach ($dataList as $item) {
            if (!empty($keyword)) {
                if (strpos($item['name'], $keyword) === false) {
                    continue;
                }
            }
            $_data[] = $item;
        }
        return $this->collectionPageQuery(collect($_data), $params, false);
    }

    /**
     * 保存数据
     * @param array $data 数据数组
     * @param int $id 主键 0 新增
     * @return Output
     */
    function save(array $data, int $id = 0): Output
    {
        if ($id) {
            $model = $this->model::find($id);
            if (empty($model)) {
                return Output::fail(__('common.tips.data_does_not_exist'), $id);
            }
            $pid = $model['pid'];
            if ($pid != $data['pid']) {
                $sequence = ConsultationWay::query()
                    ->where('hospital_id', '=', AppContext::hospitalId())
                    ->where('pid', '=', $data['pid'])->max('sequence');
                if (empty($sequence)) {
                    $sequence = 1;
                } else {
                    $sequence = $sequence + 1;
                }
                $sequence = str_pad($sequence, $data['pid'] ? 2 : 3, '0', STR_PAD_LEFT);
                $data['sequence'] = $sequence;
                if ($data['pid']) {
                    $parent = ConsultationWay::find($data['pid']);
                    $data['code'] = $parent['code'] . $data['sequence'];
                } else {
                    $data['code'] = $data['sequence'];
                }
                $len = strlen($model['code']) + 1;
                ConsultationWay::query()
                    ->where('hospital_id', '=', AppContext::hospitalId())
                    ->where('code', 'like', $model['code'] . '%')->update([
                        'code' => DB::raw("CONCAT('{$data['code']}',substr(code,$len))")
                    ]);
            }
            $model->fill($data)->save();
            return Output::success(__('common.tips.modified_successfully'), $id);
        } else {
            $sequence = ConsultationWay::query()
                ->where('hospital_id', '=', AppContext::hospitalId())
                ->where('pid', '=', $data['pid'])->max('sequence');
            if (empty($sequence)) {
                $sequence = 1;
            } else {
                $sequence = $sequence + 1;
            }
            $sequence = str_pad($sequence, $data['pid'] ? 2 : 3, '0', STR_PAD_LEFT);
            $data['sequence'] = $sequence;
            if ($data['pid']) {
                $parent = ConsultationWay::find($data['pid']);
                $data['code'] = $parent['code'] . $data['sequence'];
            } else {
                $data['code'] = $data['sequence'];
            }
            $this->model->fill($data)->save();
            return Output::success(__('common.tips.added_successfully'), $this->model['id']);
        }
    }

    /**
     * 删除后执行的方法
     * @param array $ids
     */
    protected function deleteAfter(array $ids)
    {
        $ConsultationWays = ConsultationWay::withTrashed()->whereIn('id', $ids)->get();
        foreach ($ConsultationWays as $ConsultationWay) {
            ConsultationWay::query()
                ->where('hospital_id', '=', $ConsultationWay['hospital_id'])
                ->where('code', 'like', $ConsultationWay['code'] . '%')->delete();
        }
    }


    function treeFormat($currentId)
    {
        $query = ConsultationWay::query()->where('hospital_id', '=', AppContext::hospitalId());
        $query->select('id', 'pid', 'name');
        if ($currentId) {
            $current = ConsultationWay::find($currentId);
            $query->where('code', 'not like', $current['code'] . '%');
        }
        $lis = $query->orderByDesc('weight')->get()->toArray();
        return TreeUtil::toFormat($lis, 'name');
    }
    function getModel(): BaseModel
    {
        return new ConsultationWay();
    }
}